import {ExclamationCircleOutlined, PlusOutlined} from '@ant-design/icons';
import {Button, Divider, Drawer, Form, Input, InputNumber, message, Modal, Popover, Radio, Select, Tag} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import PurchaseApplyForm from './components/PurchaseApplyForm';
import {addRule, queryMaterialList, queryRule, removeRule, updateRule, queryMaterialOne} from './service';
import {queryAccount} from '@/services/system'
import PurchaseForm from "@/pages/purchase/purchase-apply/components/PurchaseForm";

const initRecord = {
  requestCode: '',
  materialCode: '',
  materialName: '',
  materialUnit: '',
  num: 1,
  materialPrice: null,
  totalPrice: '',
  materialSupplier: '',
  remark: '',
  materialType: 1
}

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [selectedRow, setSelectedRow] = useState({});
  const [materialList, setMaterialList] = useState([])
  const [approvalData, setApprovalData] = useState([])
  const [materialType, setMaterialType] = useState(1)
  const [requestData, setRequestData] = useState({})
  const [selectedMaterial, setSelectedMaterial] = useState({})
  const [isMaterialCodeDuplicated, setIsMaterialCodeDuplicated] = useState()
  const [materialListVisible, setMaterialListVisible] = useState(false)
  const [formTitle, setFormTitle] = useState('新增采购申请');
  const actionRef = useRef();
  const [formRef] = Form.useForm();
  const [row, setRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const {Option} = Select;
  const {Search} = Input;
  const handleUpdateModalVisible = (record) => {
    //console.log((record)
    // formRef.setFieldsValue({
    //   ...record
    // })
    setSelectedRow(record)
    setFormTitle('更新采购申请')
    handleModalVisible(true)
  }
  const handleCreateModalVisible = () => {
    // //console.log(('handleCreateModalVisible')
    // formRef.setFieldsValue({
    //   ...initRecord
    // })
    setSelectedRow({...initRecord})
    setFormTitle('新增采购申请')
    handleModalVisible(true)
  }
  const onSearchMaterialByCode = async (e) => {
    if ((e.target && e.target.value) || (!e.target && e)) {
      const param = {materialCode: e.target ? e.target.value : e, pageNum: 1, pageSize: 999999};
      const res = await queryMaterialList(param)
      setMaterialList(res.result.records)
      setMaterialListVisible(true)
    } else {
      setSelectedMaterial({})
      formRef.setFieldsValue({
        materialCode: '',
        materialName: '',
        materialUnit: '',
        materialPrice: '',
        materialSupplier: '',
      })
    }
  }

  const onNumChange = (num) => {
    // //console.log((num)
    const materialPrice = formRef.getFieldValue('materialPrice');
    if (materialPrice) {
      formRef.setFieldsValue({
        totalPrice: num * materialPrice
      })
    }
  }

  const onPriceChange = (price) => {
    // //console.log((price)
    const num = formRef.getFieldValue('num');
    if (num) {
      formRef.setFieldsValue({
        totalPrice: num * price
      })
    }
  }

  const isMaterialDuplicated = async (val) => {
    const param = {materialCode: val};
    const res = await queryMaterialOne(param)
    setIsMaterialCodeDuplicated(res.data !== null)
  }
  const handleMaterial = (record) => {
    const material = JSON.parse(record)
    setSelectedMaterial(material)
    formRef.setFieldsValue({
      ...material
    })
  }

  const materialTypeChange = (e) => {
    setMaterialType(e.target.value)
    formRef.setFieldsValue({
      ...initRecord
    })
  }

  const handleAdd = async (fields) => {
    const hide = message.loading('正在添加');

    try {
      hide();
      await addRule({...fields}).then((res) => {
        if (res && res.status === '0') {
          handleModalVisible(false)
          message.success(res.message);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message);
          return false;
        }
        return true;
      });
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
    return true;
  };
  const handleUpdate = async (fields) => {
    const hide = message.loading('正在更新');

    try {
      hide();
      await updateRule({...fields}).then((res) => {
        if (res && res.status === '0') {
          handleModalVisible(false)
          message.success(res.message);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message);
        }
        return true;
      });
      return true
    } catch (error) {
      hide();
      message.error('更新失败请重试！');
      return false;
    }
  };
  const handleRemove = async (selectedRows) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
      hide();
      await removeRule({...selectedRows}).then((res) => {
        if (res && res.status === '0') {
          handleModalVisible(false)
          message.success(res.message);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message);
          return false;
        }
        return true;
      });
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  };

  const deleteConfig = (record) => {
    Modal.confirm({
      title: '注意',
      icon: <ExclamationCircleOutlined/>,
      content: `是否要删除采购编码为 【${record.requestCode} 】的采购申请？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const success = await handleRemove(record)
      }
    });
  };

  useEffect(() => {
    queryAccount({
      pageSize: 99999,
      pageNum: 1
    }).then(res => {
      if (res && res.status === '0') {
        setApprovalData(res.result.records)
      }
    })
  }, [])

  const onApprovalSearch = (v) => {
    if (v) {
      queryAccount({
        staffName: v,
        pageSize: 99999,
        pageNum: 1
      }).then(res => {
        if (res && res.status === '0') {
          setApprovalData(res.result.records)
        }
      })
    }
  }

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '物料类型',
      dataIndex: 'materialType',
      hideInTable: true,
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return (
          <Radio.Group onChange={(e) => materialTypeChange(e)} defaultValue={1}>
            <Radio.Button value={1}>新物料</Radio.Button>
            <Radio.Button value={2}>选择已有物料</Radio.Button>
          </Radio.Group>
        );
      }
    },
    {
      title: '采购编码',
      dataIndex: 'requestCode',
      tip: '采购编码是唯一的',
      hideInForm: true,
      copyable: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input placeholder={'请输入采购编码'}/>;
      }
    },
    {
      title: '物料编码',
      dataIndex: 'materialCode',
      tip: '物料编码是唯一的',
      formItemProps: {
        rules: [
          {
            max: 10,
            message: '物料编码最大长度为10'
          },
          {
            whitespace: true,
            message: '请不要输入空格'
          },
          {
            required: true,
            message: '物料编码是必填项'
          }
        ],
        validateStatus: isMaterialCodeDuplicated ? 'error' : 'success',
        help: isMaterialCodeDuplicated ? "新增物料编码重复" : ''
      },
      valueType: 'input',
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return type === 'form' ? (
          materialType === 1 ? (
            <Search
              placeholder='请输入物料编码 格式为A0' allowClear
              onSearch={(v) => isMaterialDuplicated(v)}/>
          ) : (
            <Select showSearch
                    onSearch={(v) => onSearchMaterialByCode(v)}
                    onChange={(v) => handleMaterial(v)}
            >
              {materialList.map(item => {
                return <Option
                  key={JSON.stringify(item)}>{item.materialName}({item.materialCode})</Option>
              })}
            </Select>
          )
        ) : (<Input placeholder={'请输入物料编码'}></Input>)
      }
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      formItemProps: {
        rules: [
          {
            max: 10,
            message: '物料名称最大长度为10'
          },
          {
            whitespace: true,
            message: '请不要输入空格'
          },
          {
            required: true,
            message: '物料名称是必填项'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input disabled={materialType === 2} maxLength={11} placeholder={'请输入物料名称'}/>;
      }
    },
    {
      title: '计量单位',
      dataIndex: 'materialUnit',
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Select disabled={materialType === 2}>
          <Option value="1">个</Option>
          <Option value="2">台</Option>
          <Option value="3">块</Option>
        </Select>;
      }
    },
    {
      title: '数量',
      dataIndex: 'num',
      sorter: true,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '数量是必填项'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <InputNumber min={1} style={{width: '100%'}} onChange={(v) => onNumChange(v)}/>;
      }
    },
    {
      title: '单价（元）',
      dataIndex: 'materialPrice',
      sorter: true,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '单价是必填项'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <InputNumber disabled={materialType === 2} placeholder={'请输入单价'} suffix="元" style={{width: '100%'}}
                            onChange={(v) => onPriceChange(v)}/>;
      }
    },
    {
      title: '总价（元）',
      dataIndex: 'totalPrice',
      sorter: true,
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input disabled={true} suffix="元"/>;
      }
    },
    {
      title: '供应商',
      dataIndex: 'providerName',
      hideInSearch: true,
      // renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
      //   return <Select disabled={materialType === 2} defaultValue="2">
      //     <Option value="1">A材料有限公司</Option>
      //     <Option value="2">B打印机公司</Option>
      //     <Option value="3">C供应商</Option>
      //   </Select>;
      // }
    },
    {
      title: '付款方式',
      dataIndex: 'payType',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '月结天数',
      dataIndex: 'payDays',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '状态',
      dataIndex: 'requestStatus',
      sorter: true,
      hideInForm: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Select defaultValue={-1}>
          <Option value={-1}>全部</Option>
          <Option value={0}>草稿</Option>
          <Option value={1}>待审批</Option>
          <Option value={2}>已审批</Option>
          <Option value={3}>已驳回</Option>
        </Select>;
      },
      render: (text, record, index) => {
        return (
          <Tag color={text === 0 ? 'magenta' :
            text === 1 ? 'red' :
              text === 2 ? 'blue' : 'gold'
          }>{text === 0 ? '草稿' :
            text === 1 ? '待审批' :
              text === 2 ? '已审批' : '已驳回'}</Tag>
        )
      }
    },
    {
      title: '创建人',
      dataIndex: 'createName',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '备注',
      dataIndex: 'requestRemark',
      valueType: 'textarea',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '审批人',
      dataIndex: 'approvalBy',
      hideInTable: true,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '审批人是必填项'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Select
          showSearch
          defaultActiveFirstOption={false}
          showArrow={false}
          filterOption={false}
          onSearch={(v) => onApprovalSearch(v)}
          notFoundContent={null}
        >
          {approvalData.map(item => {
            return <Option value={item.userId} key={item.userId}>{item.staffName}</Option>
          })}
        </Select>
      }
    },
    {
      title: '审批人姓名',
      dataIndex: 'approvalName',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a onClick={() => setRow(record)}>
          详情
        </a>,
        <Divider type="vertical" style={{display: record.requestStatus === 0 ? 'block' : 'none'}}/>,
        <a style={{display: record.requestStatus === 0 ? 'block' : 'none'}}
           onClick={() => handleUpdateModalVisible(record)}>修改</a>,
        <Divider style={{display: record.requestStatus === 0 ? 'block' : 'none'}} type="vertical"/>,
        <a style={{display: record.requestStatus === 0 ? 'block' : 'none'}} onClick={() => deleteConfig(record)}>删除</a>,
      ],
    },
  ];

  const detailColumns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '采购编码',
      dataIndex: 'requestCode',
      tip: '采购编码是唯一的',
      hideInForm: true,
      copyable: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input placeholder={'请输入采购编码'}/>;
      }
    },
    {
      title: '物料编码',
      dataIndex: 'materialCode',
      tip: '物料编码是唯一的',
      formItemProps: {
        rules: [
          {
            max: 10,
            message: '物料编码最大长度为10'
          },
          {
            whitespace: true,
            message: '请不要输入空格'
          },
          {
            required: true,
            message: '物料编码是必填项'
          }
        ],
        validateStatus: isMaterialCodeDuplicated ? 'error' : 'success',
        help: isMaterialCodeDuplicated ? "新增物料编码重复" : ''
      },
      valueType: 'input',
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return type === 'form' ? (
          materialType === 1 ? (
            <Search
              placeholder='请输入物料编码 格式为A0' allowClear
              onSearch={(v) => isMaterialDuplicated(v)}/>
          ) : (
            <Select showSearch
                    onSearch={(v) => onSearchMaterialByCode(v)}
                    onChange={(v) => handleMaterial(v)}
            >
              {materialList.map(item => {
                return <Option
                  key={JSON.stringify(item)}>{item.materialName}({item.materialCode})</Option>
              })}
            </Select>
          )
        ) : (<Input placeholder={'请输入物料编码'}></Input>)
      }
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      formItemProps: {
        rules: [
          {
            max: 10,
            message: '物料名称最大长度为10'
          },
          {
            whitespace: true,
            message: '请不要输入空格'
          },
          {
            required: true,
            message: '物料名称是必填项'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input disabled={materialType === 2} maxLength={11} placeholder={'请输入物料名称'}/>;
      }
    },
    {
      title: '计量单位',
      dataIndex: 'materialUnit',
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Select disabled={materialType === 2}>
          <Option value="1">个</Option>
          <Option value="2">台</Option>
          <Option value="3">块</Option>
        </Select>;
      }
    },
    {
      title: '数量',
      dataIndex: 'num',
      sorter: true,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '数量是必填项'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <InputNumber min={1} style={{width: '100%'}} onChange={(v) => onNumChange(v)}/>;
      }
    },
    {
      title: '单价',
      dataIndex: 'materialPrice',
      sorter: true,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '单价是必填项'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <InputNumber disabled={materialType === 2} placeholder={'请输入单价'} suffix="元" style={{width: '100%'}}
                            onChange={(v) => onPriceChange(v)}/>;
      }
    },
    {
      title: '总价',
      dataIndex: 'totalPrice',
      sorter: true,
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input disabled={true} suffix="元"/>;
      }
    },
    {
      title: '供应商',
      dataIndex: 'providerName',
      hideInSearch: true,
      // renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
      //   return <Select disabled={materialType === 2} defaultValue="2">
      //     <Option value="1">A材料有限公司</Option>
      //     <Option value="2">B打印机公司</Option>
      //     <Option value="3">C供应商</Option>
      //   </Select>;
      // }
    },
    {
      title: '状态',
      dataIndex: 'requestStatus',
      sorter: true,
      hideInForm: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Select defaultValue={-1}>
          <Option value={-1}>全部</Option>
          <Option value={0}>草稿</Option>
          <Option value={1}>待审批</Option>
          <Option value={2}>已审批</Option>
          <Option value={3}>已驳回</Option>
        </Select>;
      },
      render: (text, record, index) => {
        return (
          <Tag color={text === 0 ? 'magenta' :
            text === 1 ? 'red' :
              text === 2 ? 'blue' : 'gold'
          }>{text === 0 ? '草稿' :
            text === 1 ? '待审批' :
              text === 2 ? '已审批' : '已驳回'}</Tag>
        )
      }
    },
    {
      title: '付款方式',
      dataIndex: 'payType',
      hideInSearch: true,
      hideInTable: true,
      render: (text, record) => {
        return <Tag>{text === 1 ? '现金' : '月结'}</Tag>
      }
    },
    {
      title: '月结天数',
      dataIndex: 'payDays',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '创建人',
      dataIndex: 'createName',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '备注',
      dataIndex: 'requestRemark',
      valueType: 'textarea',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '审批人',
      dataIndex: 'approvalName',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '驳回原因',
      dataIndex: 'rejectReason',
      valueType: 'textarea',
      hideInSearch: true,
      hideInTable: true,
      hideInForm: true,
    },
  ];

  // const onSubmit = async (status) => {
  //   formRef.validateFields().then(value => {
  //     const param = value;
  //     let success;
  //     if (formTitle === '更新采购申请') {
  //       param.requestId = selectedRow.requestId
  //       success = handleUpdate(param)
  //     }else {
  //       param.requestStatus = status;
  //       success = handleAdd(param)
  //     }
  //
  //     if (success) {
  //       handleModalVisible(false);
  //
  //       if (actionRef.current) {
  //         actionRef.current.reload();
  //       }
  //     }
  //   })
  //
  // }
  const onSubmit = async (data) => {
    const param = data;
    let success;
    if (formTitle === '更新采购申请') {
      param.requestId = selectedRow.requestId
      success = handleUpdate(param)
    } else {
      success = handleAdd(param)
    }

    if (success) {
      handleModalVisible(false);
    }
  }

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="requestCode"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleCreateModalVisible()}>
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={async (params, sorter, filter) => {
          const param = {...params, pageNum: params.current};
          if (param.requestStatus === -1) {
            param.requestStatus = null;
          }
          const res = await queryRule(param)
          return {
            data: res.result.records,
            success: true,
            total: res.result.total
          }
        }}
        columns={columns}
        // rowSelection={{
        //   onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        // }}
      />

      {/*<PurchaseApplyForm title={formTitle} onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}*/}
      {/*                   onSubmit={(status) => onSubmit(status)}>*/}
      {/*  <ProTable*/}
      {/*    onSubmit={async (value) => {*/}
      {/*      const success = await handleAdd(value);*/}

      {/*      if (success) {*/}
      {/*        handleModalVisible(false);*/}

      {/*        if (actionRef.current) {*/}
      {/*          actionRef.current.reload();*/}
      {/*        }*/}
      {/*      }*/}
      {/*    }}*/}
      {/*    form={{*/}
      {/*      form: formRef,*/}
      {/*      layout: 'horizontal',*/}
      {/*      labelAlign: 'left',*/}
      {/*      initialValues: {...initRecord}*/}
      {/*    }}*/}
      {/*    rowKey="key"*/}
      {/*    type="form"*/}
      {/*    columns={columns}*/}
      {/*  />*/}
      {/*</PurchaseApplyForm>*/}
      {
        createModalVisible ?
          <PurchaseForm title={formTitle} requestData={selectedRow} onCancel={() => handleModalVisible(false)}
                        modalVisible={createModalVisible} onSubmit={(data) => onSubmit(data)}/>
          : <></>
      }
      {/*<PurchaseForm title={formTitle} requestData={selectedRow} onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible} onSubmit={(data) => onSubmit(data)}/>*/}

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.requestCode && (
          <ProDescriptions
            column={2}
            title={row?.materialCode}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.requestCode,
            }}
            columns={detailColumns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
